package com.sixmac.controller;

import com.sixmac.annotation.AuthUser;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.*;
import com.sixmac.service.SimulateService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

/**
 * Created by admin on 2018/7/11.
 */
@Controller
@RequestMapping("/api/simulate")
public class SimulateController extends ApiController {
    @Autowired
    SimulateService simulateService;

    /**
     * @api {post} /api/simulate/index   模拟考试首页
     * @apiName simulate.index
     * @apiGroup simulate
     * @apiParam {String}  token  token
     * @apiParam {String}  name  搜索值，可以为空
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiSuccess {String} data.rows.id 考试id
     * @apiSuccess {String} data.rows.status 考试状态 1已经考试2未考试 type==1调用getErrorRecord接口
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.title 考试标题
     * @apiSuccess {String} data.rows.score 分数
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/index")
    public AjaxResult index(ClienUser user, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "6") Integer size, String name) {
        StringBuilder sb = new StringBuilder();
        sb.append("select * from t_examin where 1=1 ");
        if (name != null) {
            sb.append("  and title like '%" + name + "%'");
        }
        sb.append(" and type = 1 ");
        BladePage<Map> mapBladePage = Db.paginate(sb.toString(), null, page, size);
        for (Map m : mapBladePage.getRows()) {
            Integer eid = Convert.toInt(m.get("id"));
            ExaminRecord examinRecord = Blade.create(ExaminRecord.class).findFirstBy("examinId=#{eid} and userId=#{uid}", getCMap().put("eid", eid).put("uid", user.getId()));
            if (examinRecord != null) {
                m.put("status", 1);
                m.put("score", examinRecord.getSource());
            } else {
                m.put("status", 2);
                m.put("score", "0");
            }

        }
        return json(mapBladePage);

    }

    /**
     * @api {post} /api/simulate/getExamin   考试题目（返回所有题目的id）
     * @apiName simulate.getExamin
     * @apiGroup simulate
     * @apiParam {String}  token  token
     * @apiParam {String}  id  考试id
     * @apiSuccess {String} data.rows.examin.examinTime 考试时间分钟为单位
     * @apiSuccess {String} data.rows.examin.image 题目图片
     * @apiSuccess {String} data.rows.examin.pass 合格分数
     * @apiSuccess {String} data.rows.examin.require 考试要求
     * @apiSuccess {String} data.rows.examin.title 考试标题
     * @apiSuccess {String} data.rows.examin.type 1考试题目2章节测试
     * @apiSuccess {String} data.rows.info.count 题目数量
     * @apiSuccess {String} data.rows.info.ids 题目的ids
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getExamin")
    public AjaxResult getExamin(ClienUser user, Integer id) {
        Examin examin = Blade.create(Examin.class).findById(id);
        if (examin == null) {
            return error("考试找不到");
        }
        Map map = Db.selectOne("select count(*) as count,group_concat(id) as ids from t_examin_topic t where t.examineId = #{id}", getCMap().put("id", id));
        String ids[] = Convert.toStr(map.get("ids")).split(",");
        Map m = getCMap().put("examin", examin).put("info", map).put("ids", ids).put("user", user);
        return json(m);
    }

    /**
     * @api {post} /api/simulate/getExaminById   通过题目的id获取题目(考试)
     * @apiName simulate.getExaminById
     * @apiGroup simulate
     * @apiParam {String}  id  题目id
     * @apiSuccess {String} data.rows.topic.choice 1单选 2多择题3判断题
     * @apiSuccess {String} data.rows.topic.image 题目图片为空则不显示，多个图片用,分隔
     * @apiSuccess {String} data.rows.topic.isTrue 正确答案，多选题目用,分隔
     * @apiSuccess {String} data.rows.topic.name 题目
     * @apiSuccess {String} data.rows.list.content 问题内容
     * @apiError {Integer} 1
     */
    @RequestMapping("/getExaminById")
    public AjaxResult getExaminById(Integer id) {
        ExaminTopic examinTopic = Blade.create(ExaminTopic.class).findById(id);
        if (examinTopic == null) {
            return error("题目找不到");
        }
        List lists = Blade.create(ExaminTopicAnswer.class).findBy("topicId=#{id}", getCMap().put("id", examinTopic.getId()));
        Map map = getCMap().put("topic", examinTopic).put("list", lists);
        return json(map);
    }

    /**
     * @api {post} /api/simulate/result   提交考试信息(考试)
     * @apiName simulate.result
     * @apiGroup simulate
     * @apiParam {String}  token  token
     * @apiParam {String}  examinId  考试id
     * @apiParam {String}  error  考试信息 比如[{"id":1,"choice":2},{"id":5,"choice":"2,3"}]id错题的id，choice错题的选项，从1开始
     * @apiSuccess {String} data.rows.topic.source 分数
     * @apiSuccess {String} data.rows.topic.errorCount 错题数量
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/result")
    public AjaxResult result(ClienUser user, Integer examinId, Integer source, Integer total, String error) {
        return simulateService.saveResult(user, examinId, error);
    }

    /**
     * @api {post} /api/simulate/recent   最近考试记录
     * @apiName simulate.recent
     * @apiGroup simulate
     * @apiParam {String}  token  token
     * @apiSuccess {String} data.rows.topic.title 考试名称
     * @apiSuccess {String} data.rows.topic.id 考试id
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/recent")
    public AjaxResult recent(ClienUser user) {
        Map mm = Db.selectOne("   select e.title,e.id from t_examin_record r inner join t_examin e on e.id = r.examinId  where r.userId = 3 order by r.createtime desc", getCMap().put("userId", user.getId()));
        return json(getCMap().put("r", mm));
    }


    /**
     * @api {post} /api/simulate/getExaminList   通过题目的ids返回所有题目
     * @apiName simulate.getExaminList
     * @apiGroup simulate
     * @apiDescription 批量返回所有题目lists集合
     * @apiParam {String}  token  token
     * @apiParam {String}  ids  考试题目的ids
     * @apiSuccess {String} data.rows.topic.choice 1单选 2多择题3判断题
     * @apiSuccess {String} data.rows.topic.image 题目图片为空则不显示，多个图片用,分隔
     * @apiSuccess {String} data.rows.topic.isTrue 正确答案，多选题目用,分隔
     * @apiSuccess {String} data.rows.topic.name 题目
     * @apiSuccess {String} data.rows.list.content 问题内容
     * @apiSuccess {String} data.rows.info.total 题目数量
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getExaminList")
    public AjaxResult getExaminList(ClienUser user, String ids) {
        AjaxResult res = new AjaxResult();
        List<Map> list = Db.selectList(" select t.id,t.examineId,t.name,t.choice,t.image,t.reach,t.isTrue,a.content from t_examin_topic t inner join t_examin_topic_answer a on t.id=a.topicId  where 1=1 and t.id in (#{join(ids)})", CMap.init().put("ids", Convert.toStrArray(ids)));
        return res.setData(CMap.init().put("list", list).put("total", list.size()));
    }

    /**
     * @api {post} /api/simulate/getErrorRecord   获取用户做过的题目
     * @apiName simulate.getErrorRecord
     * @apiGroup simulate
     * @apiDescription 批量返回所有题目lists集合
     * @apiParam {String}  token  token
     * @apiParam {String}  examinId  考试的id,比如2
     * @apiSuccess {String} data.rows.topic.ids 所有题目的ids
     * @apiSuccess {String} data.rows.topic.result 用户做题的记录
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getErrorRecord")
    public AjaxResult getErrorRecord(ClienUser user, Integer examinId) {
        return simulateService.getUserExaminRecord(user, examinId);
    }


    @Test
    public void te1() {
        List s = new ArrayList();
        Map map1 = new HashMap();
        map1.put("id", 1);
        map1.put("choice", 2);
        Map map2 = new HashMap();
        map2.put("id", 1);
        map2.put("choice", "2,3");
        Map map3 = new HashMap();
        map3.put("id", 1);
        map3.put("choice", 2);
        s.add(map1);
        s.add(map2);
        s.add(map3);
        String tt = JsonKit.toJson(s);
        System.out.print(tt);
    }

    @Test
    public void te2() {
        SortedMap<String, String> sortedMap = new TreeMap<String, String>();
        sortedMap.put("1", "a");
        sortedMap.put("5", "b");
        sortedMap.put("2", "c");
        sortedMap.put("4", "d");
        sortedMap.put("3", "e");
        for (String key : sortedMap.values()) {
            System.out.print(key);
        }

    }


}
